<?php 
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\controller;


use AlibabaCloud\AmqpOpen\V20191212\DeleteBinding;
use app\admin\service\StudentService;
use app\admin\model\School;
use app\admin\model\Grade;
use app\admin\model\Clazz;
use think\Db;

/**
 * 学生管理-控制器
 * @author 牧羊人
 * @since: 2024/10/16
 * Class Student
 * @package app\admin\controller
 */
class Student extends Backend
{
    protected $userId = 0;
    /**
     * 初始化方法
     * @author 牧羊人
     * @since: 2024/10/16
     */
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->service = new StudentService();
        // 解析Token获取用户ID
        $token = request()->header("Authorization");
        $token = str_replace("Bearer ", null, $token);
        $jwt = new \Jwt();
        $this->userId = $jwt->verifyToken($token);
    }

    //保存信息
    public function saveInfo($avatar)
    {
        try {
            \AliFaceBodyService::saveFace($this->userId, $avatar, 'student');
            Db::table('think_student')
                ->where('id', $this->userId)
                ->update(['avatar' => $avatar]);

            return $this->jsonReturn(message('success'));
        } catch (\Exception $exception) {
            return $this->jsonReturn(message($exception->getMessage(), false));
        }
    }

    public function getUserInfo()
    {
        $input = input();
        if(isset($input['roletype']) && $input['roletype'] == 2){
            $row = Db::table('think_user')->where('mark',1)->find($this->userId);
            if($row){
                $row['avatar'] = appendDomain($row['avatar']);
                $row['roll'] = $row['mobile'];
                $map = [
                    'mark' => 1,
                ];
                $c = Db::table('think_clazz')->where($map)
                    ->where('find_in_set(' . $row['id']. ',teacher) ')
                    ->find();
                $row['class_string'] = $c?$c['name']:'';
                if($c){
                    $map = [
                        'organization' => $c['organization'],
                        'id' => $row['grade'],
                        'mark' => 1,
                    ];
                    $g = Db::table('think_grade')->where($map)->find();
                    $row['grade_string'] = $g?$g['name']:'';
                }else {
                    $row['grade_string'] = '';
                }
            }
        }else{
            $row = Db::table('think_student')->where('mark',1)->find($this->userId);
            if($row){
                $row['avatar'] = appendDomain($row['avatar']);
                $row['roll'] = $row['id_card'];
                $map = [
                    'organization' => $row['school_id'],
                    'id' => $row['grade_id'],
                    'mark' => 1,
                ];
                $g = Db::table('think_grade')->where($map)->find();
                $row['grade_string'] = $g?$g['name']:'';
                $map = [
                    'organization' => $row['school_id'],
                    'grade' => $row['grade_id'],
                    'id' => $row['class_id'],
                    'mark' => 1,
                ];
                $c = Db::table('think_clazz')->where($map)->find();
                $row['class_string'] = $c?$c['name']:'';
            }
        }

        $result = message('成功', true, $row);
        return $this->jsonReturn($result);
    }
    /**
     * 导入Excel
     * @author 牧羊人
     * @since 2021/5/24
     */
    public function importExcel()
    {
        $error = "";
        // 上传文件(非图片)
        $result = upload_file('file', '', $error);
        if (!$result) {
            return $this->jsonReturn(message($error, false));
        }
        // 文件路径
        $filePath = UPLOAD_TEMP_PATH . $result;
        if (!file_exists($filePath)) {
            return $this->jsonReturn(message("文件不存在", false));
        }
        // 读取文件
        $objPHPExcel = \PHPExcel_IOFactory::load($filePath); //获取sheet表格数目
        $sheetCount = $objPHPExcel->getSheetCount(); //默认选中sheet0表
        $sheetSelected = 0;
        $objPHPExcel->setActiveSheetIndex($sheetSelected); //获取表格行数
        $rowCount = $objPHPExcel->getActiveSheet()->getHighestRow(); //获取表格列数
        $columnCount = $objPHPExcel->getActiveSheet()->getHighestColumn();
        
        // 计数器
        $arr = [];
        // 先对表格进行检查  学籍号不能重复、唯一
        for ($row = 2; $row <= $rowCount; $row++) {
            // 学籍号
            $id_card = $objPHPExcel->getActiveSheet()->getCell("G" . $row)->getValue();
            if(Db::name('student')->where(['id_card'=>$id_card,'mark'=>1])->count() > 0){
                $arr[] = $id_card;
            }
        }
        
        if(count($arr) > 0){
            $str = implode(',', $arr);
            return $this->jsonReturn(message("学籍号[{$str}]系统已经存在", false));
        }
        
        // 计数器
        $totalNum = 0;
        // 循环读取行数据
        for ($row = 2; $row <= $rowCount; $row++) {
            // 获取列值
            $dataArr = array();
            // 学校名称
            $organization = $objPHPExcel->getActiveSheet()->getCell("A" . $row)->getValue();
            $school_id = School::where('name',$organization)->value('id');
            $dataArr['school_id'] = $school_id;
            
            // 年级名称
            $gradeName = $objPHPExcel->getActiveSheet()->getCell("B" . $row)->getValue();
            $grade_id = Grade::where(['organization'=>$school_id,'name'=>$gradeName])->value('id');
            $dataArr['grade_id'] = $grade_id;
            
            // 班级名称
            $className = $objPHPExcel->getActiveSheet()->getCell("C" . $row)->getValue();
            $dataArr['class_id'] = Clazz::where(['grade'=>$grade_id,'name'=>$className])->value('id');;
           
            
             // 姓名
            $dataArr['name'] = $objPHPExcel->getActiveSheet()->getCell("D" . $row)->getValue();
            // 性别
            $gender = $objPHPExcel->getActiveSheet()->getCell("E" . $row)->getValue();
            // 性别:1男 2女 3保密
            switch ($gender) {
                case '男':
                    $dataArr['gender'] = 1;
                    break;
                case '女':
                    $dataArr['gender'] = 2;
                    break;
                default:
                     $dataArr['gender'] = 3;
                    break;
            }
            
             // 手机号码
            $dataArr['phone'] = $objPHPExcel->getActiveSheet()->getCell("F" . $row)->getValue();
            
            // 学籍号
            $dataArr['id_card'] = $objPHPExcel->getActiveSheet()->getCell("G" . $row)->getValue();
            
            // 插入数据
            $studentModel = new \app\admin\model\Student();
            $result = $studentModel->edit($dataArr);
            if ($result) {
                $totalNum++;
            }
        }
        return $this->jsonReturn(message("本次共导入{$totalNum}条数据", true));
    }
    
    /**
     * 获取学生列表
     * @return mixed
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function getList()
    {
        $result = $this->service->getList();
        return $this->jsonReturn($result);
    }

	
                                            	                        
}